package com.lxd.milktea.controller;

import com.lxd.milktea.VO.ResultVO;
import com.lxd.milktea.dataobject.Category;
import com.lxd.milktea.exception.SellException;
import com.lxd.milktea.form.CategoryForm;
import com.lxd.milktea.service.CategoryService;
import com.lxd.milktea.util.ResultVOUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/category")
public class CategoryController {

    private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * 类目列表
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value = "类目列表")
    @ResponseBody
    public ResultVO list() {
        Map<String, Object> map = new HashMap<>();
        List<Category> categoryList = categoryService.findAll();
        map.put("categoryList", categoryList);
        return ResultVOUtil.success(map);
    }

    /**
     * 展示
     * @param categoryId
     * @return
     */
    @GetMapping("/index")
    @ApiOperation(value = "展示类目信息")
    @ResponseBody
    public ResultVO index(@RequestParam(value = "categoryId", required = false) Integer categoryId) {
        Map<String, Object> map = new HashMap<>();
        if (categoryId != null) {
            Category productCategory = categoryService.findOne(categoryId);
            map.put("category", productCategory);
        }
        return ResultVOUtil.success(map);
    }

    /**
     * 保存/更新
     * @param form
     * @param bindingResult
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    @ApiOperation(value = "保存/更新类目信息")
    public ResultVO save(@Valid @ModelAttribute CategoryForm form,
                             BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            return ResultVOUtil.fail(500,bindingResult.getFieldError().getDefaultMessage());
        }

        Category productCategory = new Category();
        try {
            if (form.getCategoryId() != null) {
                productCategory = categoryService.findOne(form.getCategoryId());
            }
            BeanUtils.copyProperties(form, productCategory,"categoryId");
            categoryService.save(productCategory);
        } catch (SellException e) {
            return ResultVOUtil.fail(500,e.getMessage());
        }
        return ResultVOUtil.success();
    }
}
